﻿using LS.Nc6.Web.Entry.ViewModel.UI;

namespace LS.Nc6.Web.Entry.ViewComponents
{
    public class PaginationViewComponent : ViewComponent
    {
        private const int PAGE_NO_LENGTH = 5;
        private readonly ICmsChannelService _cmsChannelService;
        public PaginationViewComponent(ICmsChannelService cmsChannelService)
        {
            _cmsChannelService = cmsChannelService;
        }
        /// <summary>
        /// 初始化分页空间
        /// </summary>
        /// <param name="channelId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="totalSzie"></param>
        /// <param name="pathUrl"></param>
        /// <returns></returns>
        public  async Task<IViewComponentResult> InvokeAsync(long channelId,int pageIndex,int pageSize, int totalRow,string pathUrl)
        {
            var channelmodel = await _cmsChannelService.GetModelAsync(a=>a.Id== channelId);

            PaginationVm paginationVm = new PaginationVm();
            paginationVm.ChannelId= channelmodel.Id;
            paginationVm.TotalRows= totalRow;
            paginationVm.PageSize= pageSize;
            paginationVm.ChanIndex = channelmodel.IndexName;
            paginationVm.TotalPage = Convert.ToInt32(Math.Ceiling(paginationVm.TotalRows * 1.0 / paginationVm.PageSize));
            paginationVm.PageNo= pageIndex> paginationVm.TotalPage? paginationVm.TotalPage: pageIndex;
            paginationVm.IsPreviousPage = paginationVm.PageNo > 1;
            paginationVm.IsNextPage = paginationVm.PageNo < paginationVm.TotalPage;
            List<int> pagenums = new List<int>();
            if(paginationVm.TotalPage<= PAGE_NO_LENGTH)
            {
                for (int i = 1; i <= paginationVm.TotalPage; i++)
                {
                    pagenums.Add(i);
                }
            }
            else
            {
                if (paginationVm.PageNo <= PAGE_NO_LENGTH / 2 + 1)
                {
                    for (int i = 1; i <= PAGE_NO_LENGTH; i++)
                    {
                        pagenums.Add(i);
                    }
                }
                else if (paginationVm.PageNo>= paginationVm.TotalPage - (PAGE_NO_LENGTH-1) / 2)
                {
                    for (int i = paginationVm.TotalPage-(PAGE_NO_LENGTH-1); i <= paginationVm.TotalPage; i++)
                    {
                        pagenums.Add(i);
                    }
                }
                else
                {
                    int begin = paginationVm.PageNo - (PAGE_NO_LENGTH - 1) / 2;
                    int end = paginationVm.PageNo+ (PAGE_NO_LENGTH - 1) / 2;
                    for (int i = begin; i < end; i++)
                    {
                        pagenums.Add(begin);
                    }
                }
            }

            paginationVm.NumPage = pagenums;

            return View(paginationVm);
        }
    }
}
